#include <iostream>
#include "Merge.h"

LinkList::LinkList() : size(0)
{
    head = new Node(0);
}

void LinkList::InsertTail(const ElementType &element)
{
    Node *travelPoint = head;
    while (travelPoint->next != nullptr)
    {
        travelPoint = travelPoint->next;
    }
    travelPoint->next = new Node(element);
    size++;
}

LinkList LinkList::Merge(const LinkList *lists, int size)
{
    if (size == 0)
    {
        return lists[0];
    }
    LinkList result;
    for (int i = 0; i < size; i++)
    {
        result = result.MergeTwoLink(lists[i]);
    }
    return result;
}

LinkList LinkList::MergeTwoLink(const LinkList &list)
{
    LinkList result;
    Node *p1 = head->next;
    Node *p2 = list.head->next;
    while (p1 && p2)
    {
        if (p1->value < p2->value)
        {
            result.InsertTail(p1->value);
            p1 = p1->next;
        }
        else
        {
            result.InsertTail(p2->value);
            p2 = p2->next;
        }
    }
    while (p1)
    {
        result.InsertTail(p1->value);
        p1 = p1->next;
    }
    while (p2)
    {
        result.InsertTail(p2->value);
        p2 = p2->next;
    }
    return result;
}

void LinkList::show()
{
    Node *travelPoint = head->next;
    while (travelPoint != nullptr)
    {
        std::cout << travelPoint->value << " ";
        travelPoint = travelPoint->next;
    }
    std::cout << std::endl;
}